package com.cloud.business.config;

import com.alibaba.fastjson.JSON;
import com.cloud.business.exception.FeignException;
import com.cloud.business.dto.ResponseVO;
import com.cloud.business.enums.ResponseEnum;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import java.nio.charset.Charset;

/**
 * @description :Feign调用异常处理
 * 如果没有此处理器，默认的
 */
@Slf4j
@Configuration
public class FeignErrorDecoderConfig implements ErrorDecoder{

    @Override
    public Exception decode(String s, Response response) {
        try {
            if (response.body() != null) {
                String json = Util.toString(response.body().asReader(Charset.defaultCharset()));
                log.error("【ErrorDecoder】" + json);
                ResponseVO responseVO = JSON.parseObject(json, ResponseVO.class);

                return new FeignException(responseVO.getCode(), responseVO.getMsg());
            }
        } catch (Exception var4) {
            var4.printStackTrace();
            return new FeignException(var4.getMessage());
        }
        return new FeignException(ResponseEnum.FAILURE);

    }

}
